package com.sjx.boundarycallback.decoration;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Shader;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.sjx.boundarycallback.R;

/**
 * Created by sjx on 6/1/22
 * 绘制蒙版，和利用onDrawOver()函数
 */
public class BitMapItemDecoration extends RecyclerView.ItemDecoration {

    private final Paint mPaint;
    private final Bitmap mMedalBmp;

    public BitMapItemDecoration(Context context) {
        super();
        mPaint = new Paint();
        mPaint.setColor(Color.GREEN);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;
        mMedalBmp = BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon_2_1, options);
    }

    public void onDrawOver(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.onDrawOver(c, parent, state);
        //画勋章
        RecyclerView.LayoutManager manager = parent.getLayoutManager();
        if (manager == null) return;
        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = parent.getChildAt(i);
            int index = parent.getChildAdapterPosition(child);
            int left = manager.getLeftDecorationWidth(child);
            if (index % 5 == 0) {
                c.drawBitmap(mMedalBmp, left - (float) mMedalBmp.getWidth() / 2, child.getTop(), mPaint);
            }
        }

        //画蒙版
        View temp = parent.getChildAt(0);
        LinearGradient gradient = new LinearGradient(0, temp.getHeight() * 3, (float) parent.getWidth(), temp.getHeight() * 3,
                0xff0000ff, 0x000000ff, Shader.TileMode.CLAMP);
        mPaint.setShader(gradient);
        c.drawRect(0, 0, parent.getWidth(), temp.getHeight() * 3, mPaint);
    }


    @Override
    public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.onDraw(c, parent, state);
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        outRect.left = 200;
        outRect.bottom = 1;
    }

}
